import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import { getAddressNameByCode } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Select,
  Row,
  Col,
  Input,
  InputNumber,
  Upload,
  Modal,
  Button,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { TextArea } = Input;
const { Item } = Form;

interface BasicInfoProps extends FormComponentProps {
  forms: any;
  auth: string;
  dispatch?: Dispatch | any;
  detailInfo?: any;
  INITINFO?: any;
  mergeValues: (values: any) => void;
}

interface BasicInfoState {
  imageUrl: string;
  typeGarden: number;
  reviewImg: boolean;
}

@connect(({
  common: { INITINFO },
}: any) => ({ INITINFO }))

class BasicInfoElem extends Component<BasicInfoProps, BasicInfoState> {
  state: BasicInfoState = {
    imageUrl: '',
    typeGarden: 1,
    reviewImg: false,
  }

  static getDerivedStateFromProps(nextProps: BasicInfoProps, perState: BasicInfoState) {
    const { imageUrl } = perState;
    const { detailInfo } = nextProps;
    if (detailInfo && detailInfo.img && !imageUrl) {
      return ({
        imageUrl: detailInfo.img,
      });
    }
    return null;
  }

  componentDidMount() {
    this.fetchAction('common/fetchGardenType');
  }

  handleSelectGarden: any = (garden: { key: number, label: string }) => {
    const { form: { resetFields } } = this.props;
    resetFields(['orgId']);

    const { detailInfo } = this.props;
    delete detailInfo.orgId;
    this.fetchAction('common/fetchSelectOrgList', { gardenId: garden.key });
  }

  handleChageType = (typeGarden: number) => this.setState({ typeGarden });

  getBase64 = (img: any, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleUpload = ({ fileList, file }: any) => {
    const { mergeValues } = this.props;
    this.getBase64(file.originFileObj, (imageUrl: string) => {
      mergeValues({
        file: fileList.length <= 0 ? 1 : file.originFileObj,
      });
      this.setState({ imageUrl });
    });
  }

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `logisticsCenterSaveAndUpdate/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const {
      imageUrl,
      typeGarden,
      reviewImg,
    } = this.state;
    const {
      forms: { getFieldDecorator },
      detailInfo,
      INITINFO: {
        gardenList,
        selectOrgList,
      },
      auth,
    } = this.props;

    const garden: any = [];
    gardenList.map((item: any) => {
      if (typeGarden === 1) garden.push(item);
      if (item.type === typeGarden) garden.push(item);
      return false;
    });

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    return (
      <Card title="基本信息" bordered={false}>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="　　物流中心" colon={false}>
              {getFieldDecorator('name', {
                initialValue: detailInfo.name,
                rules: [{ required: true, message: '请输入物流中心' }],
              })(
                <Input
                  allowClear
                  disabled={detailInfo.id && auth !== 'root'}
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　学校/小区" colon={false}>
              {getFieldDecorator('garden', {
                initialValue: detailInfo.gardenId && {
                  key: detailInfo.gardenId,
                  label: detailInfo.gardenName
                    || (garden.length && garden.find((item: any) => (
                      item.id === detailInfo.gardenId
                    )).name),
                },
                rules: [{ required: true, message: '请选择学校/小区' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择"
                  labelInValue
                  disabled={detailInfo.id && auth !== 'root'}
                  onChange={this.handleSelectGarden}
                  filterOption={(input: any, option: any) => (
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )}
                >
                  {garden.map((item: any) => (
                    <Option value={item.id} key={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="物流中心编号" colon={false}>
              {getFieldDecorator('code', {
                initialValue: detailInfo.code,
                rules: [{ required: false }],
              })(
                <Input
                  allowClear
                  placeholder="提交信息后自动生成"
                  disabled
                />,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="　　　　部门" colon={false}>
              {getFieldDecorator('orgId', {
                initialValue: detailInfo.orgId,
                rules: [{ required: true, message: '请选择部门' }],
              })(
                <Select disabled={detailInfo.id && auth !== 'root'} placeholder="请选择">
                  {selectOrgList.map((item: any) => (
                    <Option value={item.id} key={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　　省市区" colon={false}>
              {getFieldDecorator('code', {
                initialValue: detailInfo.pareaCode && (
                  getAddressNameByCode({
                    pareaCode: detailInfo.pareaCode,
                    caredCode: detailInfo.careaCode,
                    dareaCode: detailInfo.dareaCode,
                  })),
              })(
                <Input
                  allowClear
                  placeholder="根据所属小区对应的省市区获得"
                  disabled
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　店面等级" colon={false}>
              {getFieldDecorator('level', {
                initialValue: detailInfo.level,
                rules: [{ required: true, message: '请选择店面等级' }],
              })(
                <Select disabled={detailInfo.id && auth !== 'root'} placeholder="请选择">
                  <Option value={1}>普通店</Option>
                  <Option value={2}>标准店</Option>
                </Select>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="　　定编人数" colon={false}>
              {getFieldDecorator('staffNum', {
                initialValue: detailInfo.staffNum,
                rules: [{ required: true, message: '请输入定编人数' }],
              })(
                <InputNumber
                  disabled={detailInfo.id && auth !== 'root'}
                  min={0}
                  max={9999}
                  placeholder="请输入"
                  style={{ width: '100%' }}
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　街道信息" colon={false}>
              {getFieldDecorator('townName', {
                initialValue: detailInfo.townName,
              })(
                <Input
                  allowClear
                  placeholder="根据所属小区对应的省市区获得"
                  disabled
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　客服电话" colon={false}>
              {getFieldDecorator('servicePhone', {
                initialValue: detailInfo.servicePhone,
                rules: [{ required: true, message: '请输入客户服务电话' }],
              })(<Input allowClear disabled={detailInfo.id && auth === 'other'} placeholder="请输入" />)}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="　　　　经度" colon={false}>
              {getFieldDecorator('longitude', {
                initialValue: detailInfo.longitude,
                rules: [{ required: true, message: '请输入经度' }],
              })(
                <Input
                  allowClear
                  type="number"
                  disabled={detailInfo.id && auth === 'other'}
                  step={0.00000000000001}
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　　　　纬度" colon={false}>
              {getFieldDecorator('latitude', {
                initialValue: detailInfo.latitude,
                rules: [{ required: true, message: '请输入纬度' }],
              })(
                <Input
                  type="number"
                  disabled={detailInfo.id && auth === 'other'}
                  step={0.00000000000001}
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>

        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="　　详细地址" colon={false}>
              {getFieldDecorator('address', {
                initialValue: detailInfo.address,
                rules: [{ required: true, message: '请输入详细地址' }],
              })(
                <TextArea
                  disabled={detailInfo.id && auth !== 'root'}
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24} style={{ display: 'flex', alignItems: 'center' }}>
            <Item label="　　门店图片" colon={false}>
              {getFieldDecorator('file_img', {
                initialValue: imageUrl,
              })(
                <Upload
                  accept=".png,.jpg,.jpeg,.gif"
                  listType="picture-card"
                  disabled={detailInfo.id && auth !== 'root'}
                  className="uploadBtn"
                  showUploadList={false}
                  onChange={this.handleUpload}
                >
                  {imageUrl
                    ? <img src={imageUrl} alt="门店图片" style={{ width: '100%', height: '100%' }} />
                    : uploadButton}
                </Upload>,
              )}
            </Item>
            {imageUrl && <span className="operLink" onClick={() => this.setState({ reviewImg: true })}>预览</span>}
          </Col>
        </Row>

        <Modal
          title="图片预览"
          visible={reviewImg}
          width={600}
          onCancel={() => this.setState({ reviewImg: false })}
          footer={[
            <div key="ok" style={{ textAlign: 'center' }}>
              <Button
                type="primary"
                onClick={() => this.setState({ reviewImg: false })}
              >
                确定
              </Button>
            </div>,
          ]}
        >
          <img src={imageUrl} alt="门店图片" style={{ width: '100%', height: '100%' }} />
        </Modal>
      </Card>
    );
  }
}

export default Form.create<BasicInfoProps>()(BasicInfoElem);
